<template>
  <a-modal
    :title="title"
    width="80%"
    :dialog-style="{ top: '20px' }"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleSubmit"
    @cancel="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-divider orientation="left"><span style="color: #1890ff">商品信息</span></a-divider>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入商品编号" v-decorator="[ 'serialNo', {rules: [{ required: true, message: '请输入商品编号!' }]}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入商品名称" v-decorator="[ 'name', {rules: [{ required: true, message: '请输入商品名称!' }]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="价格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入商品价格" v-decorator="[ 'price', {rules: [{ required: true, message: '请输入商品价格!' }]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="所属分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <tree-select
                style="width:100%"
                :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                :treeData="treeData"
                v-decorator="['varietyId', {rules: [{ required: true, message: '请选择商品的分类!' }]}]"
                placeholder="请选择商品的分类"
              >
              </tree-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="库存" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入商品库存" v-decorator="[ 'quantity', {rules: [{ required: true, message: '请输入商品库存!' }]}]" />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select placeholder="请选择商品单位" v-decorator="[ 'unitId', {rules: [{ required: true, message: '请选择商品单位!' }]}]">
                <a-select-option v-for="(item,index) in unitList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="有效期"
            >
              <a-range-picker v-decorator="['expiryDateRange', {rules: [{ type: 'array', required: true, message: '请选择有效期!' }],}]" />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="封面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                v-decorator="[
                  'fileField',
                  {
                    valuePropName: 'fileList',
                    getValueFromEvent: normFile,
                    initialValue: [],
                    preserve: true,
                    rules: [{ required: true, message: '请选择封面图片!' }]
                  },
                ]"
                listType="picture-card"
                :beforeUpload="handleBeforeUploadPhoto"
                :customRequest="uploadPhoto"
                :remove="removePhoto"
                @preview="handlePreviewPhoto"
              >
                <div v-if="showUpload">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">点击上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item hidden>
              <a-input
                v-decorator="[ 'coverFileId',{ rules: [
                  { validator: validateCoverFileId }
                ] } ]"/>
            </a-form-item>
          </a-col>

        </a-row>

        <a-divider orientation="left"><span style="color: #1890ff">商品详情</span></a-divider>
        <a-form-item>
          <editor v-decorator="[ 'detail', {rules: [{ required: true, message: '请输入商品详情!' }]}]" triggerChange></editor>
        </a-form-item>

      </a-form>
    </a-spin>

    <a-modal width="100%" :visible="previewVisible" :footer="null" @cancel="previewVisible = false" centered>
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>

  </a-modal>

</template>

<script>
import pick from 'lodash.pick'
import Editor from '@/components/editor/Editor'
import { TreeSelect } from 'ant-design-vue'
import { FormModalMixin } from '@/mixins/FormModalMixin'
import { apiQueryCommodityVarietyTree, apiQueryCommodityById, apiSaveCommodity, apiUpdateCommodity } from '@/api/commodity'
import { apiQueryUnitList } from '@/api/unit'
import { apiUploadFile, VIEW_FILE_URL } from '@/api/file'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { COMMODITY_RECYCLE_STATUS_ENUM, COMMODITY_ISSUE_STATUS_ENUM } from '@/store/mutation-types'

export default {
  name: 'CommodityModal',
  components: {
    Editor, TreeSelect
  },
  mixins: [FormModalMixin],
  data () {
    return {
      moment,
      treeData: [],
      unitList: [],
      previewVisible: false,
      previewImage: '',
      showUpload: true,
      dateFormat: 'YYYY-MM-DD',
      issueStatusEnum: COMMODITY_ISSUE_STATUS_ENUM,
      recycleStatusEnum: COMMODITY_RECYCLE_STATUS_ENUM
    }
  },
  methods: {
    show (title, record) {
      this.resetFields()
      this.model = {}
      this.showUpload = true
      this.visible = true
      this.title = title
      this.queryUnitList()
      this.loadVarietyTree()
      if (record) {
        apiQueryCommodityById(record.id).then(res => {
          this.model = Object.assign({}, res.data)
          this.$nextTick(() => {
            const formData = pick(this.model, 'serialNo', 'name', 'price', 'varietyId', 'unitId', 'quantity', 'coverFileId', 'detail')
            formData.expiryDateRange = [moment(res.data.expiryStartDate, this.dateFormat), moment(res.data.expiryEndDate, this.dateFormat)]
            this.showUpload = false
            this.form.setFieldsValue(formData)
            this.form.setFieldsValue({
              fileField: [{
                uid: this.model.coverFileId,
                status: 'done',
                url: VIEW_FILE_URL + this.model.coverFileId,
                name: '封面'
              }]
            })
          })
        })
      }
    },
    loadVarietyTree () {
      const that = this
      apiQueryCommodityVarietyTree().then(res => {
        that.treeData = that.getTreeData(res.data)
      })
    },
    queryUnitList () {
      const that = this
      apiQueryUnitList().then(res => {
        that.unitList = res.data.content
      })
    },
    getTreeData (list) {
      const treeData = []
      for (let i = 0; i < list.length; i++) {
        const temp = {
          title: list[i].name,
          value: list[i].id,
          key: list[i].id
        }
        if (list[i].children !== null && list[i].children.length > 0) {
          temp.children = [...this.getTreeData(list[i].children)]
        }
        treeData.push(temp)
      }
      return treeData
    },
    normFile (e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleBeforeUploadPhoto (file, fileList) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      return new Promise((resolve, reject) => {
        if (!isJPG) {
          this.$message.error('请选择jpg或png文件！')
          reject(file)
        } else if (fileList.length > 1) {
          this.$message.error('最多上传1个文件！')
        } else {
          resolve(file)
        }
      })
    },
    uploadPhoto (e) {
      this.showUpload = false
      const formData = new FormData()
      formData.append('multipartFile', e.file)
      apiUploadFile(formData, (progress) => {
        console.log('apiUploadFile=', progress)
        let percent = (progress.loaded / progress.total) * 100
        if (percent > 99) {
          percent = 99
        }
        e.onProgress({ percent: percent })
      }).then(res => {
        console.log('uploadPhoto=>', res)
        this.form.setFieldsValue({
          coverFileId: res.data.id
        })
        e.onSuccess()
      }).catch(err => {
        e.onError(err, err.message)
      })
    },
    removePhoto () {
      this.showUpload = true
      this.form.setFieldsValue({
        fileField: [],
        coverFileId: null
      })
    },
    handlePreviewPhoto (file) {
      console.log(file)
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    validateCoverFileId (rule, value, callback) {
      if (!value) {
        this.form.setFieldsValue({
          fileField: []
        })
        this.form.validateFields(['fileField'], { force: true })
        this.showUpload = true
      }
      callback()
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const formData = pick(Object.assign(this.model, values), 'serialNo', 'name', 'price', 'varietyId', 'unitId', 'quantity', 'coverFileId', 'detail')
          formData.expiryStartDate = values.expiryDateRange[0].format('YYYY-MM-DD') + ' 00:00:00'
          formData.expiryEndDate = values.expiryDateRange[1].format('YYYY-MM-DD') + ' 23:59:59'
          formData.recycleStatus = this.recycleStatusEnum.NORMAL.KEY
          formData.issueStatus = this.issueStatusEnum.RELEASE.KEY
          let obj
          if (this.model.id) {
            obj = apiUpdateCommodity(this.model.id, formData)
          } else {
            obj = apiSaveCommodity(formData)
          }
          obj.then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
